package com.gzhryc.shared_device.oem.h5.agent.controllers.api.v1.team;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.data.ValidateTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelation;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationBusinessConfig;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationDevice;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationFuncModel;
import com.gzhryc.shared_device.oem.code.agent.dao.enums.AgentRelationEnum;
import com.gzhryc.shared_device.oem.code.agent.dao.enums.AgentRelationFuncModelEnum;
import com.gzhryc.shared_device.oem.code.agent.dao.models.RelationUserDeviceCount;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationBusinessConfigService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationDeviceService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationFuncModelService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationService;
import com.gzhryc.shared_device.oem.code.agent.services.dto.AgentRelationDeviceSearch;
import com.gzhryc.shared_device.oem.code.agent.services.dto.AgentRelationSearch;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.config.dao.db.FuncModel;
import com.gzhryc.shared_device.oem.code.config.dao.enums.FuncModelEnum;
import com.gzhryc.shared_device.oem.code.config.services.FuncModelService;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceProfitUser;
import com.gzhryc.shared_device.oem.code.place.dao.models.IncomeRatioContent;
import com.gzhryc.shared_device.oem.code.place.dao.models.RoleTypePlaceCount;
import com.gzhryc.shared_device.oem.code.place.dao.models.UserProfitPlaceCount;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.place.services.PlaceProfitUserService;
import com.gzhryc.shared_device.oem.code.place.services.dto.PlacePhysicalStoreSearch;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.services.UserService;
import com.gzhryc.shared_device.oem.h5.agent.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.h5.agent.LoginUser;
import com.gzhryc.shared_device.oem.h5.agent.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.TeamRoleTypeListRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.TeamRoleTypeListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.TeamUserAddRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.TeamUserBusiConfigDelRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.TeamUserBusiConfigSaveRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.TeamUserDeviceListRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.TeamUserDeviceListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.TeamUserFuncModelUpdateRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.TeamUserInfoRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.TeamUserInfoResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.TeamUserListRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.TeamUserListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.TeamUserPlaceListRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.TeamUserPlaceListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.TeamUserPowerUpdateRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.team.TeamUserUpdateRequest;

/**
 * 我的团队(员工)
 * @version 2023--06-01
 */
public class TeamUserController {

    static Logger log = Logger.getLogger(TeamUserController.class);

    @Route(value = "/agent/api/v1/team/user/list.data")
    public TeamUserListResponse list(HttpServletRequest request) {
        TeamUserListResponse apiResp = new TeamUserListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        TeamUserListRequest apiReq = WebUtils.getJsonRequest(request, TeamUserListRequest.class);
        if (apiReq != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if(loginUser != null && ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                Integer pageNo = apiReq.getBody().getPageNo() == null?1:apiReq.getBody().getPageNo();

                AgentRelationSearch search = new AgentRelationSearch();
                search.setUserId(loginUser.getId());
                search.setRoleType(apiReq.getBody().getRoleType());
                search.setTrim(apiReq.getBody().getTrim());

                List<AgentRelation> agentRelationList = AgentRelationService.self().findJoinBySearch(search,pageNo,WebConstants.PAGE_LIMIT);
                if (agentRelationList != null && agentRelationList.size() > 0) {
                    apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setItems(new ArrayList<>());
                    List<Long> relationUserIds = new ArrayList<>();
                    for (AgentRelation agentRelation : agentRelationList) {
                        relationUserIds.add(agentRelation.getRelationUserId());
                    }

                    List<RelationUserDeviceCount>  relationUserDeviceCountList = AgentRelationDeviceService.self().findDeviceCountByUserKeys(loginUser.getId(),relationUserIds);
                    List<UserProfitPlaceCount> userProfitPlaceCountList = PlaceProfitUserService.self().findPlaceCountByUserKeys(loginUser.getId(),relationUserIds);
                    for (AgentRelation agentRelation : agentRelationList) {
                        TeamUserListResponse.Item item = new TeamUserListResponse.Item();
                        item.setUserId(agentRelation.getRelationUserId());
                        item.setUserName(agentRelation.getRelationUser().getName());
                        item.setUserPhone(agentRelation.getRelationUser().getPhone());
                        item.setRoleType(agentRelation.getRoleType());
                        item.setRoleTypeName(agentRelation.getRoleTypeName());
                        item.setNote(agentRelation.getNote());
                        item.setLastLoginDate(agentRelation.getLastLoginDate());
                        item.setCreateDate(agentRelation.getCreateDate());
                        item.setDeviceCount(0);
                        item.setPlaceCount(0);
                        if(relationUserDeviceCountList != null && relationUserDeviceCountList.size() > 0){
                            for(RelationUserDeviceCount relationUserDeviceCount : relationUserDeviceCountList){
                                if(relationUserDeviceCount.getRelationUserId().equals(item.getUserId())){
                                    if(relationUserDeviceCount.getDeviceCount() != null) {
                                        item.setDeviceCount(relationUserDeviceCount.getDeviceCount().intValue());
                                    }
                                    break;
                                }
                            }
                        }
                        if(userProfitPlaceCountList != null && userProfitPlaceCountList.size() > 0){
                            for(UserProfitPlaceCount userProfitPlaceCount : userProfitPlaceCountList){
                                if(userProfitPlaceCount.getUserId().equals(item.getUserId())){
                                    if(userProfitPlaceCount.getPlaceCount() != null) {
                                        item.setPlaceCount(userProfitPlaceCount.getPlaceCount().intValue());
                                    }
                                    break;
                                }
                            }
                        }
                        apiResp.getBody().getItems().add(item);
                    }
                }
            }
        }
        return apiResp;
    }
    
    @Route(value = "/agent/api/v1/team/user/add.do")
    public DefaultAPIResponse add(HttpServletRequest request){
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR,"新增失败");
        TeamUserAddRequest apiReq = WebUtils.getJsonRequest(request, TeamUserAddRequest.class);
        if (apiReq != null && StringTools.isNotBlank(apiReq.getBody().getPhone()) && apiReq.getBody().getRoleType() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                if(!ValidateTools.isPhone(apiReq.getBody().getPhone())){
                    apiResp.setMsg("手机号不正确，请检查");
                    return apiResp;
                }

                User user = UserService.self().getByPhone(apiReq.getBody().getPhone());
                Long userId = apiReq.getBody().getUserId();
                if(userId != null){
                    if(user == null || !user.getId().equals(userId)){
                        apiResp.setMsg("未找到用户信息");
                        return apiResp;
                    }

                    AgentRelation agentRelation = new AgentRelation();
                    agentRelation.setUserId(loginUser.getId());
                    agentRelation.setRelationUserId(userId);
                    agentRelation.setRoleType(apiReq.getBody().getRoleType());
                    agentRelation.setNote(apiReq.getBody().getNote());

                    try {
                        if(AgentRelationService.self().add(agentRelation,apiReq.getBody().getFuncModelIds())){
                            apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                        }
                    } catch (LogicException e) {
                        apiResp.setMsg(e.getMessage());
                    }
                }else {
                    if(user != null){
                        apiResp.setMsg("用户已存在，请重新上一步");
                        return apiResp;
                    }else {
                        if(StringTools.isBlank(apiReq.getBody().getNickname())){
                            apiResp.setMsg("请填写用户姓名");
                            return apiResp;
                        }
                    }

                    user = new User();
                    user.setNickname(apiReq.getBody().getNickname());
                    user.setPhone(apiReq.getBody().getPhone());

                    AgentRelation agentRelation = new AgentRelation();
                    agentRelation.setUserId(loginUser.getId());
                    agentRelation.setRoleType(apiReq.getBody().getRoleType());
                    agentRelation.setNote(apiReq.getBody().getNote());

                    try {
                        if(AgentRelationService.self().add(agentRelation,user,apiReq.getBody().getFuncModelIds())){
                            apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                        }
                    } catch (LogicException e) {
                        apiResp.setMsg(e.getMessage());
                    }
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/team/user/info.data")
    public TeamUserInfoResponse info(HttpServletRequest request) {
        TeamUserInfoResponse apiResp = new TeamUserInfoResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        TeamUserInfoRequest apiReq = WebUtils.getJsonRequest(request, TeamUserInfoRequest.class);
        if(apiReq != null && apiReq.getBody().getUserId() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                AgentRelation agentRelation = AgentRelationService.self().getJoinByKeys(loginUser.getId(), apiReq.getBody().getUserId());
                if (agentRelation != null) {
                    apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                    apiResp.getBody().setUserId(agentRelation.getRelationUserId());
                    apiResp.getBody().setUserName(agentRelation.getRelationUser().getName());
                    apiResp.getBody().setUserPhone(agentRelation.getRelationUser().getPhone());
                    if(StringTools.isNotBlank(agentRelation.getRelationUser().getFaceImg())){
                    	 String resDomain = WebConstants.getResDomain(request);
                        apiResp.getBody().setUserFaceImg(WebUtils.setHttpDomain(resDomain,agentRelation.getRelationUser().getFaceImg()));
                    }
                    apiResp.getBody().setNote(agentRelation.getNote());
                    apiResp.getBody().setRoleType(agentRelation.getRoleType());
                    apiResp.getBody().setRoleTypeName(agentRelation.getRoleTypeName());
                    apiResp.getBody().setLastLoginDate(agentRelation.getLastLoginDate());
                    apiResp.getBody().setCreateDate(agentRelation.getCreateDate());
                    apiResp.getBody().setDeviceCount(0);
                    apiResp.getBody().setPlaceCount(0);

                    AgentRelationDeviceSearch deviceSearch = new AgentRelationDeviceSearch();
                    deviceSearch.setUserId(loginUser.getId());
                    deviceSearch.setRelationUserId(agentRelation.getRelationUserId());
                    Long deviceCount = AgentRelationDeviceService.self().countJoinBySearch(deviceSearch);
                    if (deviceCount != null) {
                        apiResp.getBody().setDeviceCount(deviceCount.intValue());
                    }

                    Long placeCount = PlaceProfitUserService.self().countByUserKeys(loginUser.getId(), agentRelation.getRelationUserId());
                    if (placeCount != null) {
                        apiResp.getBody().setPlaceCount(placeCount.intValue());
                    }

                    List<AgentRelationFuncModel> agentRelationFuncModelList = AgentRelationFuncModelService.self().findJoinByUserKeys(loginUser.getId(), agentRelation.getRelationUserId());
                    if (agentRelationFuncModelList != null && agentRelationFuncModelList.size() > 0) {
                        apiResp.getBody().setFuncModelItems(new ArrayList<>());
                        for (AgentRelationFuncModel agentRelationFuncModel : agentRelationFuncModelList) {
                            TeamUserInfoResponse.FuncModelItem item = new TeamUserInfoResponse.FuncModelItem();
                            item.setId(agentRelationFuncModel.getFuncModel().getId());
                            item.setName(agentRelationFuncModel.getFuncModel().getName());
                            item.setIconImg(agentRelationFuncModel.getFuncModel().getIconUrl());
                            item.setState(agentRelationFuncModel.getState());
                            apiResp.getBody().getFuncModelItems().add(item);
                        }
                    }
                }else{
                    apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限查看");
                }
            }
        }
        return apiResp;
    }
    
    @Route(value = "/agent/api/v1/team/user/update.do")
    public DefaultAPIResponse update(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "修改失败");
        TeamUserUpdateRequest apiReq = WebUtils.getJsonRequest(request, TeamUserUpdateRequest.class);
        if (apiReq != null && apiReq.getBody().getUserId() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                try {
                    if (AgentRelationService.self().updateNote(loginUser.getId(),apiReq.getBody().getUserId(),apiReq.getBody().getNote())) {
                        apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                    }
                } catch (LogicException e) {
                    apiResp.setMsg(e.getMessage());
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/team/user/func_model/update.do")
    public DefaultAPIResponse updateFuncModel(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "修改失败");
        TeamUserFuncModelUpdateRequest apiReq = WebUtils.getJsonRequest(request, TeamUserFuncModelUpdateRequest.class);
        if (apiReq != null && apiReq.getBody().getUserId() != null && apiReq.getBody().getFuncModelId() != null && apiReq.getBody().getState() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                AgentRelation agentRelation = AgentRelationService.self().getByKeys(loginUser.getId(),apiReq.getBody().getUserId());
                if(agentRelation == null){
                    apiResp.setMsg("未找到用户信息");
                    return apiResp;
                }
          
                AgentRelationFuncModel agentRelationFuncModel = AgentRelationFuncModelService.self()
           			 .getJoinByKeys(agentRelation.getUserId(), agentRelation.getRelationUserId(), apiReq.getBody().getFuncModelId());
                FuncModel funcModel = null;
                if(agentRelationFuncModel != null) {
                	funcModel = agentRelationFuncModel.getFuncModel();
                }else {
                	funcModel = FuncModelService.self().getById(apiReq.getBody().getFuncModelId());
                }
                
                if(funcModel == null || !funcModel.getType().equals(agentRelation.getRoleType())) {
                	if(agentRelationFuncModel != null) {
                		//删除
                		try {
	                		AgentRelationFuncModelService.self().deleteByKeys(agentRelation.getUserId(), agentRelation.getRelationUserId()
	                				, apiReq.getBody().getFuncModelId());
                		}catch (LogicException e) {
                            //--
                        }
                	}
                	apiResp.setMsg("无权限设置此功能模块");
                    return apiResp;
                }
                
                if(apiReq.getBody().getState() == 2) {
                	//开启
                	if(agentRelationFuncModel != null) {
                		if(FuncModelEnum.State.Default.index().equals(agentRelationFuncModel.getFuncModel().getState())) {
                			//直接删除
                			try {
	                			if(AgentRelationFuncModelService.self().deleteByKeys(agentRelation.getUserId(), agentRelation.getRelationUserId()
		                				, apiReq.getBody().getFuncModelId())) {
	                				apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
	                			}
                			} catch (LogicException e) {
                                apiResp.setMsg(e.getMessage());
                            }
                		}else {
                			if (AgentRelationFuncModelService.self().updateState(agentRelation.getUserId(), agentRelation.getRelationUserId()
	                				, apiReq.getBody().getFuncModelId(),AgentRelationFuncModelEnum.State.Open.index())) {
                                apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                            }
                		}
                	}else {
                		agentRelationFuncModel = new AgentRelationFuncModel();
                        agentRelationFuncModel.setUserId(loginUser.getId());
                        agentRelationFuncModel.setRelationUserId(apiReq.getBody().getUserId());
                        agentRelationFuncModel.setFuncModelId(funcModel.getId());
                        agentRelationFuncModel.setState(AgentRelationFuncModelEnum.State.Open.index());
                        agentRelationFuncModel.setCreateDate(new Date());
                        try {
                            if (AgentRelationFuncModelService.self().add(agentRelationFuncModel)) {
                                apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                            }
                        } catch (LogicException e) {
                            apiResp.setMsg(e.getMessage());
                        }
                	}
                }else {
                	//关闭
                	if(agentRelationFuncModel != null) {
                		if(FuncModelEnum.State.Default.index().equals(agentRelationFuncModel.getFuncModel().getState())) {
                			if(AgentRelationFuncModelEnum.State.Open.index().equals(agentRelationFuncModel.getState())) {
                				if (AgentRelationFuncModelService.self().updateState(agentRelationFuncModel.getUserId()
                              		  ,agentRelationFuncModel.getRelationUserId(),agentRelationFuncModel.getFuncModelId()
                              		  ,AgentRelationFuncModelEnum.State.Close.index())) {
                                    apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                                }
                			}else {
                				apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                			}
                		}else {
                			//直接删除
                			try {
	                			if(AgentRelationFuncModelService.self().deleteByKeys(agentRelation.getUserId(), agentRelation.getRelationUserId()
	                    				, apiReq.getBody().getFuncModelId())) {
	                				apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
	                			}
                			} catch (LogicException e) {
                                apiResp.setMsg(e.getMessage());
                            }
                		}
                	}else if(FuncModelEnum.State.Default.index().equals(funcModel.getState())) {
                		agentRelationFuncModel = new AgentRelationFuncModel();
                        agentRelationFuncModel.setUserId(loginUser.getId());
                        agentRelationFuncModel.setRelationUserId(apiReq.getBody().getUserId());
                        agentRelationFuncModel.setFuncModelId(funcModel.getId());
                        agentRelationFuncModel.setState(AgentRelationFuncModelEnum.State.Close.index());
                        agentRelationFuncModel.setCreateDate(new Date());
                        try {
                            if (AgentRelationFuncModelService.self().add(agentRelationFuncModel)) {
                                apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                            }
                        } catch (LogicException e) {
                            apiResp.setMsg(e.getMessage());
                        }
                	}else {
                		apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                	}
                }
            }
        }
        return apiResp;
    }
    
    @Route(value = "/agent/api/v1/team/user/power/update.do")
    public DefaultAPIResponse updatePower(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "修改失败");
        TeamUserPowerUpdateRequest apiReq = WebUtils.getJsonRequest(request, TeamUserPowerUpdateRequest.class);
        if (apiReq != null && apiReq.getBody().getUserId() != null && StringTools.isNotBlank(apiReq.getBody().getCode()) && apiReq.getBody().getState() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                AgentRelation agentRelation = AgentRelationService.self().getByKeys(loginUser.getId(),apiReq.getBody().getUserId());
                if(agentRelation == null){
                    apiResp.setMsg("未找到用户信息");
                    return apiResp;
                }
                
                AgentRelation updateEntity = null;
                if(AgentRelationEnum.PowerType.CanUndeployDevice.name().equals(apiReq.getBody().getCode())) {
                	updateEntity = new AgentRelation();
                	updateEntity.setUserId(agentRelation.getUserId());
                	updateEntity.setRelationUserId(agentRelation.getRelationUserId());
                	if(apiReq.getBody().getState() == 2) {
                		//开启
                		updateEntity.setCanUndeployDevice(1);
                	}else {
                		updateEntity.setCanUndeployDevice(0);
                	}
                }
                
                if(updateEntity != null) {
	                try {
						if(AgentRelationService.self().updatePower(updateEntity)) {
							apiResp.setCode(ClientAPICodeConstants.SUCCESS, null); 
						}
					} catch (LogicException e) {
						apiResp.setMsg(e.getMessage());
					}
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/team/user/busi_config/save.do")
    public DefaultAPIResponse saveBusiConfig(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "保存失败");
        TeamUserBusiConfigSaveRequest apiReq = WebUtils.getJsonRequest(request, TeamUserBusiConfigSaveRequest.class);
        if (apiReq != null && apiReq.getBody().getUserId() != null && StringTools.isNotBlank(apiReq.getBody().getBusinessType())
        		&& apiReq.getBody().getIncomeRatio() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                AgentRelation agentRelation = AgentRelationService.self().getByKeys(loginUser.getId(),apiReq.getBody().getUserId());
                if(agentRelation == null){
                    apiResp.setMsg("未找到用户信息");
                    return apiResp;
                }
                
                AgentRelationBusinessConfig arBusiConfig = AgentRelationBusinessConfigService.self().getByKeys(loginUser.getId(),
                		apiReq.getBody().getUserId(), apiReq.getBody().getBusinessType());
                if(arBusiConfig != null) {
                	arBusiConfig.setIncomeRatio(apiReq.getBody().getIncomeRatio());
                	arBusiConfig.setEditFeeState(apiReq.getBody().getEditFeeState());
                	
                	try {
	                	if(AgentRelationBusinessConfigService.self().updateNotNull(arBusiConfig)) {
	                		apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
	                	}
                	} catch (LogicException e) {
                		apiResp.setMsg(e.getMessage());
                    }
                }else {
                	arBusiConfig = new AgentRelationBusinessConfig();
                	arBusiConfig.setUserId(loginUser.getId());
                	arBusiConfig.setRelationUserId(apiReq.getBody().getUserId());
                	arBusiConfig.setBusinessType(apiReq.getBody().getBusinessType());
                	arBusiConfig.setIncomeRatio(apiReq.getBody().getIncomeRatio());
                	arBusiConfig.setEditFeeState(apiReq.getBody().getEditFeeState());
                	
                	try {
	                	if(AgentRelationBusinessConfigService.self().add(arBusiConfig)) {
	                		apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
	                	}
	                } catch (LogicException e) {
	            		apiResp.setMsg(e.getMessage());
	                }
                }
            }
        }
        return apiResp;
    }
    
    @Route(value = "/agent/api/v1/team/user/busi_config/del.do")
    public DefaultAPIResponse delBusiConfig(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "删除失败");
        TeamUserBusiConfigDelRequest apiReq = WebUtils.getJsonRequest(request, TeamUserBusiConfigDelRequest.class);
        if (apiReq != null && apiReq.getBody().getUserId() != null && StringTools.isNotBlank(apiReq.getBody().getBusinessType())) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                try {
	                if(AgentRelationBusinessConfigService.self().deleteByKeys(loginUser.getId(), apiReq.getBody().getUserId()
	                		, apiReq.getBody().getBusinessType())) {
	                	apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
	                }
	            } catch (LogicException e) {
	        		apiResp.setMsg(e.getMessage());
	            }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/team/user/place/physical_store/list.data")
    public TeamUserPlaceListResponse placeList(HttpServletRequest request) {
        TeamUserPlaceListResponse apiResp = new TeamUserPlaceListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        TeamUserPlaceListRequest apiReq = WebUtils.getJsonRequest(request, TeamUserPlaceListRequest.class);
        if (apiReq != null && apiReq.getBody().getUserId() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                List<PlaceProfitUser> placeProfitUserList = PlaceProfitUserService.self().findByUserKeys(loginUser.getId(),apiReq.getBody().getUserId());
                if(placeProfitUserList != null && placeProfitUserList.size() > 0){
                    List<Long> placeIds = new ArrayList<>();
                    for(PlaceProfitUser placeProfitUser : placeProfitUserList){
                        placeIds.add(placeProfitUser.getPlaceId());
                    }

                    Integer pageNo = apiReq.getBody().getPageNo() == null?1:apiReq.getBody().getPageNo();

                    PlacePhysicalStoreSearch search = new PlacePhysicalStoreSearch();
                    search.setName(apiReq.getBody().getTrim());
                    search.setPlaceIds(placeIds);
                    List<PlacePhysicalStore> data = PlacePhysicalStoreService.self().findJoinBySearch(search,pageNo,WebConstants.PAGE_LIMIT);
                    if (data != null && data.size() > 0) {
                        apiResp.setCode(ClientAPICodeConstants.SUCCESS, null);
                        apiResp.getBody().setItems(new ArrayList<>());

                        String resDomain = WebConstants.getResDomain(request);
                        for (PlacePhysicalStore place : data) {
                            TeamUserPlaceListResponse.Item item = new TeamUserPlaceListResponse.Item();
                            item.setId(place.getId());
                            item.setName(place.getName());
                            item.setProvince(place.getProvince());
                            item.setCity(place.getCity());
                            item.setCityArea(place.getCityArea());
                            if (StringTools.isNotBlank(place.getThumbnailImg())) {
                                item.setImgUrl(resDomain + place.getThumbnailImg());
                            }

                            for(PlaceProfitUser placeProfitUser : placeProfitUserList){
                                if(placeProfitUser.getPlaceId().equals(item.getId())){
                                    item.setRoleType(placeProfitUser.getRoleType());
                                    item.setRoleTypeName(placeProfitUser.getRoleTypeName());
                                    item.setJoinDate(placeProfitUser.getCreateDate());
                                    //分成比例
                                    if (StringTools.isNotBlank(placeProfitUser.getIncomeRatioContent())) {
                                        item.setIncomeRatioItems(new ArrayList<>());
                                        IncomeRatioContent incomeRatioContent = JsonTools.fromJson(placeProfitUser.getIncomeRatioContent(), IncomeRatioContent.class);
                                        for (IncomeRatioContent.Item ratioItem : incomeRatioContent.getItems()) {
                                            TeamUserPlaceListResponse.IncomeRatioItem incomeRatioItem = new TeamUserPlaceListResponse.IncomeRatioItem();
                                            incomeRatioItem.setBusinessType(ratioItem.getBusinessType());
                                            incomeRatioItem.setBusinessTypeName(EBusinessType.note(ratioItem.getBusinessType()));
                                            incomeRatioItem.setIncomeRatio(ratioItem.getIncomeRatio());
                                            item.getIncomeRatioItems().add(incomeRatioItem);
                                        }
                                    }
                                }
                            }
                            apiResp.getBody().getItems().add(item);
                        }
                    }
                }
            }
        }
        return apiResp;
    }
    
    @Route(value = "/agent/api/v1/team/user/device/list.data")
    public TeamUserDeviceListResponse deviceList(HttpServletRequest request) {
    	TeamUserDeviceListResponse apiResp = new TeamUserDeviceListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        TeamUserDeviceListRequest apiReq = WebUtils.getJsonRequest(request, TeamUserDeviceListRequest.class);
        if (apiReq != null && apiReq.getBody().getUserId() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                Integer pageNo = apiReq.getBody().getPageNo() == null?1:apiReq.getBody().getPageNo();

                AgentRelationDeviceSearch search = new AgentRelationDeviceSearch();
                search.setUserId(loginUser.getId());
                search.setRelationUserId(apiReq.getBody().getUserId());
                search.setDeviceSn(apiReq.getBody().getTrim());
                List<AgentRelationDevice> agentRelationDeviceList = AgentRelationDeviceService.self().findJoinBySearch(search,pageNo,WebConstants.PAGE_LIMIT);
                if(agentRelationDeviceList != null && agentRelationDeviceList.size() > 0){
                    apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                    apiResp.getBody().setItems(new ArrayList<>());
                    for(AgentRelationDevice agentRelationDevice : agentRelationDeviceList){
                    	TeamUserDeviceListResponse.DeviceItem item = new TeamUserDeviceListResponse.DeviceItem();
                        item.setDeviceSn(agentRelationDevice.getDeviceSn());
                        item.setDeviceTypeId(agentRelationDevice.getDevice().getDeviceTypeId());
                        item.setDeviceTypeName(agentRelationDevice.getDevice().getDeviceTypeName());
                        item.setDeviceFunCodes(agentRelationDevice.getDevice().getDeviceFunCodes());
                        item.setDeviceFunNames(agentRelationDevice.getDevice().getDeviceFunNames());
                        item.setPlaceId(agentRelationDevice.getDevice().getPlaceId());
                        item.setPlaceName(agentRelationDevice.getDevice().getPlaceName());
                        item.setPlaceAreaName(agentRelationDevice.getDevice().getAreaName());
                        apiResp.getBody().getItems().add(item);
                    }
                }
            }
        }
        return apiResp;
    }
    
    @Route(value = "/agent/api/v1/team/user/role_type/list.data")
    public TeamRoleTypeListResponse roleTypeList(HttpServletRequest request) {
    	TeamRoleTypeListResponse apiResp = new TeamRoleTypeListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
    	TeamRoleTypeListRequest apiReq = WebUtils.getJsonRequest(request, TeamRoleTypeListRequest.class);
        if (apiReq != null && apiReq.getBody().getUserId() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null && ERoleType.Agent.index().equals(loginUser.getRoleType())) {
            	
                AgentRelationDeviceSearch search = new AgentRelationDeviceSearch();
                search.setUserId(loginUser.getId());
                search.setRelationUserId(apiReq.getBody().getUserId());

                List<RoleTypePlaceCount> rolePlaceCountList = PlaceProfitUserService.self().findRolePlaceCountByUserKeys(loginUser.getId()
                		,apiReq.getBody().getUserId());
                if(rolePlaceCountList != null && rolePlaceCountList.size() > 0){
                    apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                    apiResp.getBody().setItems(new ArrayList<>());
                    for(RoleTypePlaceCount rolePlaceCount : rolePlaceCountList){
                    	TeamRoleTypeListResponse.RoleTypeItem item = new TeamRoleTypeListResponse.RoleTypeItem();
                        item.setRoleType(rolePlaceCount.getRoleType());
                        item.setRoleTypeName(ERoleType.note(rolePlaceCount.getRoleType()));
                        item.setPlaceCount(rolePlaceCount.getPlaceCount());
                        apiResp.getBody().getItems().add(item);
                    }
                }
            }
        }
        return apiResp;
    }
}
